<?php

namespace app\miniprograms\controller;

use controller\BasicAdmin;
use service\DataService;
use service\NodeService;
use service\ToolsService;
use think\App;;
use think\Db;
use think\Exception;

/**
 * 地区管理
 * Class Area
 * @package app\admin\controller
 * @author liuda <1576283429@qq.com>       // Db::table('area')->alias('A')->join('system_user U','A.create_by_id = U.id','LEFT')->select();

 * @date
 */
class Price extends BasicAdmin
{
    public $table = 'price';
    /**
     * 价格管理列表
     */
    public function index(){
        $this->title = '洗衣价格';
        //查询地区
        $session = $this->request->session();
        $user = $session['user'];  //$user['is_admin']  1为管理员  其余是供应商
        // if($user['is_admin'] !=1 ){
        //     $areasids = Db::table('machine')->field('area_id')->where("user_id ={$user['id']} ")->group('area_id')->select();
        //    if($areasids){
        //        $areasids = implode(",", array_column($areasids,'area_id'));
        //        $areas = Db::table('area')->field('id,area_name')->where("id IN({$areasids})  and is_deleted = 0")->order('id desc')->select();
        //    }else{
        //        $areas = [];
        //    }
        // }else{
            $areas = Db::table('area')->field('id,area_name')->where('is_deleted = 0')->order('id desc')->select();
        // }

        $emptyPrice = [
            0=>[
                'wash_type'=> '---------',
                'wash_price' =>'---------',
                'create_time' => 1514736000,    //2018-01-01 00:00:00
                'username' => '---------'
            ]
        ];
        if(!empty($areas)){
            foreach ($areas as $key=>$item){
                $areas[$key]['data'] = $this->getAreaPrice($item['id']);
                $areas[$key]['data'] = $areas[$key]['data'] ? $areas[$key]['data'] :$emptyPrice;
            }
        }
        $this->assign('list', $areas);
        return $this->fetch();
    }


    private function getAreaPrice($areaId){
        $prices =  Db::table('price')->alias('P')->join('system_user U','P.create_by_id = U.id')->field('wash_type,wash_price,P.create_time,U.username')->where(['P.area_id'=>$areaId,'P.is_deleted'=>0])->select();
        if($prices){
            foreach ($prices as $key => $item){
                switch ($item['wash_type']){
                    case 1:
                        $prices[$key]['wash_type'] = '标准洗';
                        break;
                    case 2:
                        $prices[$key]['wash_type'] = '快洗';
                        break;
                    case 3:
                        $prices[$key]['wash_type'] = '单脱';
                        break;
                    case 4:
                        $prices[$key]['wash_type'] = '大物件洗';
                        break;
                }
            }
            return $prices;
        }

    }


    /**
     * 添加地区
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function add()
    {
        $areas = Db::table('area')->field('id,area_name')->where('is_deleted = 0')->select();
        $this->assign('areas', $areas);
        return $this->_form($this->table, 'form');
    }


    /**
     * 表单数据默认处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _form_filter(&$data)
    {
        if ($this->request->isPost()) {    //添加处理
            //地区校验
            $area = $this->request->post('area');
            if(empty($area)  || !is_numeric($area)){
                $this->error('请选择正确的地区');
            }
            $isEdit = $this->request->post('edit');
            //编辑操作将以前的数据删除
            if($isEdit){
                Db::name('price')->where('area_id',$area)->delete();
            }
            //洗衣类型和价格校验   洗衣类型 1为标准洗 2为快洗 3为单脱 4为大物件洗
            $data = []; //保存的数据
            $wash_type = [
                1 => "标准洗",
                2 => "快洗",
                3 => "单脱",
                4 => "大物件洗",
            ];
            foreach ($wash_type as $key=>$keyword){
              $wash_type = $key;
              $wash_price = $this->request->post($key);
              if($wash_price){
                  if(is_numeric($wash_price) && $wash_price> 0){
                      $item = [
                        'wash_type' => $wash_type,
                        'wash_price' => $wash_price,
                          'area_id' => $area,
                          'create_time'=> time(),
                          'create_by_id' =>session('user.id'),
                          'is_deleted'=> 0
                      ];
                      $data[] = array_push($data,$item);
                  }else{
                      $this->error($keyword.'价格填写有误!');
                  }

              }
            }
            foreach ($data as $key => $val){
                if(empty($val['area_id']) || empty($val['area_id'])) unset($data[$key]);
            }
            if(count($data) <1) $this->error("请填写正确的信息");
            try{
                Db::name('price')->insertAll($data);
                $this->success('恭喜, 数据保存成功!', '');
            }catch (Exception $e){
                $this->error('添加数据失败，请稍后再试！');
            }
        } else {  //添加显示

        }
    }


    //同一地区的洗衣类型和价格是否存在

    private function priceIsExit($item){
        return Db::table('price')->field(count(1))->where(['area_id'=>$item['area_id'],'wash_type'=>$item['wash_type'],'is_deleted'=>0])->find();
    }

   /*
    * 编辑价格
    */
    public function edit()
    {
        $area_id = $this->request->get('id');
        $areas = Db::table('area')->field('id,area_name')->where('is_deleted = 0')->select(); //获取地区
        $this->assign('areas', $areas);
        $this->assign('area_id', $area_id);
        //获取此地区下的洗衣类型和价格
        $price = Db::table('price')->field('wash_type,wash_price')->where(['area_id'=>$area_id,'is_deleted'=>0])->select();
        $price = call_user_func(function ()use ($price){
            $newPrices = [];
            foreach ($price as $key=>$item){
                $newPrices[$item['wash_type']] = $item['wash_price'];
            }
            return $newPrices;
        });
        $this->assign('edit', true);
        $this->assign('price', $price);
        return $this->_form($this->table, 'form');
    }


    /**
     * 删除价格
     */
    public function del(){
        $area_id = $this->request->get('id');
        if(empty($area_id)  || !is_numeric($area_id)){
            $this->error('请选择正确的地区');
        }
        $isDel = Db::name('price')->where('area_id',$area_id)->delete();
        if ($isDel) {
            $this->success("价格删除成功！", '');
        }
        $this->error("地区价格失败，请稍候再试！");
    }



}